package com.jf.cloud.service.sysmanager.remote;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.jf.cloud.service.sysmanager.common.db.Query;
import com.jf.cloud.service.sysmanager.common.util.JsonUtil;
import com.jf.cloud.service.sysmanager.common.util.MD5;
import com.jf.cloud.service.sysmanager.common.util.StringUtil;
import com.jf.cloud.service.sysmanager.common.util.TokenUtil;
import com.jf.cloud.service.sysmanager.dao.ISysMenuService;
import com.jf.cloud.service.sysmanager.dao.ISysRoleService;
import com.jf.cloud.service.sysmanager.dao.ISysRoleVsMenuService;
import com.jf.cloud.service.sysmanager.dao.ISysStaffService;
import com.jf.cloud.service.sysmanager.entity.SysMenu;
import com.jf.cloud.service.sysmanager.entity.SysRole;
import com.jf.cloud.service.sysmanager.entity.SysRoleVsMenu;
import com.jf.cloud.service.sysmanager.entity.SysStaff;
import com.jf.cloud.service.sysmanager.handler.TokenHandler;
import com.jf.cloud.service.sysmanager.support.entity.Result;
import com.jf.cloud.service.sysmanager.support.web.BaseController;

import net.sf.json.JSONArray;

@Controller
public class LoginController extends BaseController {

	private static Logger log = LoggerFactory.getLogger(LoginController.class);

	@Resource
	private ISysStaffService staffService;

	@Resource
	private ISysMenuService menuService;

	@Resource
	private ISysRoleVsMenuService roleMenuService;

	@Resource
	private ISysRoleService roleService;
	
	@Resource
	private TokenHandler tokenHandler;


	/**
	 * 登录
	 * 
	 * @author 朱建文 创建时间：2017年12月9日 上午10:58:54
	 */
	@RequestMapping("/login")
	public String login(HttpServletRequest request, HttpServletResponse response) {
//		SysStaff user = (SysStaff) request.getSession().getAttribute("user");
		try {
			
			//判断登录IP校验END
			SysStaff user = null;
			String token = (String) request.getSession().getAttribute("token");
			String sysStaffJson = tokenHandler.getSysStaffByToken(token);
			String roleId = SYS_ADMIN_ID;
			if (sysStaffJson != null) {
				user = JsonUtil.toPOJO(sysStaffJson, SysStaff.class);
				
				// 查询菜单信息
				if (!user.getStaffAccount().equals(SYS_ADMIN)) {
					roleId = user.getStaffType();
				}
				Map<String, Object> result = getMenuListForLeftTree(roleId);
				request.setAttribute("indexUrl", result.get("indexUrl"));
				request.setAttribute("menus", JSONArray.fromObject(result.get("menus")).toString());
				
				// 把登录成功后token保存
				token = TokenUtil.buildToken();
				tokenHandler.putSysToken(token, user.getRowId() + "", JsonUtil.toJSON(user));
				request.setAttribute("token", token);
				return "index";
			}
			
			// 新登陆
			String username = getStringValue(request, "username");
			String password = getStringValue(request, "password");
			
			Query query = new Query();
			query.put("STAFF_ACCOUNT", username);
			user = staffService.find(query);
			if (user == null) {
				request.setAttribute("code", 1);
				request.setAttribute("msg", "帐号不存在，请联系管理员!");
				return "welcome";
			} else {
				if ("0".equals(user.getUseFlag()) || "1".equals(user.getDelFlag())) {
					request.setAttribute("code", 1);
					request.setAttribute("msg", "帐号已禁用，请联系管理员!");
					return "welcome";
				}
			}
			
			Query query1 = new Query();
			query1.put("ROW_ID", user.getStaffType());
			query1.put("DEL_FLAG", 0);
			SysRole role = roleService.find(query1);
			if (role == null) {
				request.setAttribute("code", 1);
				request.setAttribute("msg", "帐号对应角色已被删除，请联系管理员!");
				return "welcome";
			}

			String val = MD5.encodeUtf8(password);
			if (val.equals(user.getStaffPwd())) {

				// 修改最后登录时间
				staffService.updateLastLoginTime(user.getRowId());
				request.getSession().setAttribute("user", user);
				request.setAttribute("code", 1);
				request.setAttribute("msg", "欢迎" + user.getStaffAccount() + "登录!");
				
				// 查询菜单信息
				if (!user.getStaffAccount().equals(SYS_ADMIN)) {
					roleId = user.getStaffType();
				}
				Map<String, Object> result = getMenuListForLeftTree(roleId);
				request.setAttribute("indexUrl", result.get("indexUrl"));
				request.setAttribute("menus", JSONArray.fromObject(result.get("menus")).toString());
				
				// 把登录成功后token保存
				token = TokenUtil.buildToken();
				tokenHandler.putSysToken(token, user.getRowId() + "", JsonUtil.toJSON(user));
				request.setAttribute("token", token);
				
				return "index";
			} else {
				request.setAttribute("code", 1);
				request.setAttribute("msg", "用户名或者密码错误!");
				return "welcome";
			}

		} catch (Exception e) {
			log.error("***************用户登录出错了", e);
			request.setAttribute("code", 1);
			request.setAttribute("msg", "用户登录异常!");
			return "welcome";
		}
	}

	/**
	 * 页面左侧树形菜单展示数据
	 * 
	 * @author 朱建文 创建时间：2017年12月9日 上午10:58:39
	 */
	public Map<String, Object> getMenuListForLeftTree(String roleId) {
		Map<String, Object> result = new HashMap<String, Object>();
		String indexUrl = "";
		// 1.查询菜单
		Query query = new Query();
		query.put("DEL_FLAG", 0);// 未删除的数据
		query.put("MENU_FLAG", "0").notEqual();// 不获取按钮类型
		query.orderBy(" order by PARENT_ID,ORDER_NUM");
		List<SysMenu> findList = menuService.findList(query);
		List<Map<String, Object>> menus = new ArrayList<Map<String, Object>>();

		// 2.查询员工权限
		Set<Long> menuIds = new HashSet<Long>();
		if (!SYS_ADMIN_ID.equals(roleId)) {
			Query queryRole = new Query();
			queryRole.put("ROLE_ID", roleId);
			List<SysRoleVsMenu> roleMenuList = this.roleMenuService.findList(queryRole);
			for (SysRoleVsMenu roleVsMenu : roleMenuList) {
				menuIds.add(roleVsMenu.getMenuId());
			}
		}

		for (int i = 0; i < findList.size(); i++) {
			HashMap<String, Object> hashMap = new HashMap<String, Object>();
			if (findList.get(i).getParentId() == null || findList.get(i).getParentId() == 0) {// 一及菜单
				hashMap.put("url", ""); // 一级目录不需要url
				// hashMap.put("isOpen",
				// "1".equals(findList.get(i).getOpenFlag()) ? true : false);
				// 是否默认打开
				hashMap.put("icon", "glyphicon glyphicon-th-list"); // 默认图标
				hashMap.put("id", findList.get(i).getRowId()); // 默认图标
				hashMap.put("text", findList.get(i).getMenuName());
				if (StringUtil.isNotEmpty(findList.get(i).getIcon())) {
					hashMap.put("icon", findList.get(i).getIcon()); // 设置了自定义图标
				}
				List<Map<String, Object>> chMenus = new ArrayList<Map<String, Object>>();
				for (int j = 0; j < findList.size(); j++) {
					HashMap<String, Object> hashMap2 = new HashMap<String, Object>();
					if (findList.get(j) != null && findList.get(j).getParentId() != null && findList.get(j).getParentId() != 0
							&& hashMap.get("id").toString().equals(findList.get(j).getParentId() + "") && (SYS_ADMIN_ID.equals(roleId) || menuIds.contains(findList.get(j).getRowId()))) {
						hashMap2.put("url", findList.get(j).getUrl());
						hashMap2.put("targetType", "iframe-tab");
						hashMap2.put("icon", "glyphicon glyphicon-list-alt"); // 默认图标
						hashMap2.put("id", findList.get(j).getRowId()); // 默认图标
						hashMap2.put("text", findList.get(j).getMenuName());
						if (StringUtil.isNotEmpty(findList.get(j).getIcon())) {
							hashMap2.put("icon", findList.get(j).getIcon());
							// 设置了自定义图标
						}
						if (!StringUtil.notNull(indexUrl)) { // 首页加载时需要展示的页面
							indexUrl = findList.get(j).getUrl();
						}
						chMenus.add(hashMap2);
					}
				}
				if (chMenus != null && chMenus.size() > 0) {
					hashMap.put("children", chMenus);
					menus.add(hashMap);
				}

			}
		}
		result.put("menus", menus);
		result.put("indexUrl", indexUrl);
		return result;
	}
	
	/**
	 * 退出
	 * 
	 * @author 朱建文 创建时间：2017年12月20日 下午1:51:23
	 */
	@ResponseBody
	@RequestMapping("/logout")
	public String logout(String token, HttpServletRequest request){
		Result<SysStaff> result = new Result<SysStaff>();
		result.setCode(-1);
		result.setMessage("退出登录出错了");
		try {
			SysStaff user = (SysStaff) request.getSession().getAttribute("user");
			tokenHandler.removeSysToken(token, JsonUtil.toJSON(user));
			result.setCode(0);
		} catch (Exception e) {
			log.error("退出出错", e);
		}
		return result.toString();
	}
}
